package com.company.cloud.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.company.cloud.web.models.SitMapModel;
import com.company.cloud.web.render.Render;
import com.company.cloud.web.render.RenderFactory;
import com.company.cloud.web.render.kit.HttpContextUtils;
import com.company.cloud.web.service.WebArtService;
import com.company.cloud.web.service.WebIndexService;
import com.company.cloud.web.service.WebPrdService;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.*;

@Controller
public class IndexController {

    @Autowired
    private WebIndexService webIndexService;

    @Autowired
    private WebPrdService webPrdService;

    @Autowired
    private WebArtService webArtService;

    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request, @CookieValue(value = "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE", defaultValue = "zh-CN") String i18n) {
        System.out.println("++++++++++++ index");
        Map<String, Object> indexMap = webIndexService.getPageIndexData();
        model.addAttribute("category", indexMap.get("category"));
        String domain = request.getServerName();

        model.addAttribute("domain", domain);

        Map<String, Object> menusMap = webArtService.staticPageTree("top");
        model.addAttribute("menu", menusMap);


        // model.addAttribute("menu",indexMap.get("menu"));

        //model.addAttribute("footer",indexMap.get("footer"));
        model.addAttribute("friendLink", indexMap.get("friendLink"));
        model.addAttribute("copyright", indexMap.get("copyright"));

        model.addAttribute("homeActivity", indexMap.get("homeActivity"));
        model.addAttribute("homeArtist", indexMap.get("homeArtist"));
        model.addAttribute("homeProductSort", indexMap.get("homeProductSort"));
        model.addAttribute("homeProductCate", indexMap.get("homeProductCate"));
        Map<String, Object> footer = webArtService.staticPageTree("bottom");
        model.addAttribute("footer", footer);
        model.addAttribute("i18n", i18n);
        if (i18n.toString().equals("zh-CN")) {
            model.addAttribute("homeService", indexMap.get("homeService"));
            model.addAttribute("homeBanner", indexMap.get("homeBanner"));
        } else {
            model.addAttribute("homeService", indexMap.get("homeServiceen"));
            model.addAttribute("homeBanner", indexMap.get("homeBanneren"));
        }


        model.addAttribute("homeProudct1", indexMap.get("homeProudct1"));
        model.addAttribute("homeProudct2", indexMap.get("homeProudct2"));
        model.addAttribute("homeProudct3", indexMap.get("homeProudct3"));
        model.addAttribute("homeProudct4", indexMap.get("homeProudct4"));
        model.addAttribute("homeProudct5", indexMap.get("homeProudct5"));
        model.addAttribute("homeProudct6", indexMap.get("homeProudct6"));
        model.addAttribute("homeProudct7", indexMap.get("homeProudct7"));
        model.addAttribute("homeProudct8", indexMap.get("homeProudct8"));
        model.addAttribute("homeProudct9", indexMap.get("homeProudct9"));

        Map<String, String> params = new HashMap<String, String>();
        params.put("num", "4");
        params.put("categoryId", "8");
        Map<String, Object> pMap = webPrdService.getPrdRecommendList(params);
        model.addAttribute("pMap", pMap);


        Map<String, String> params2 = new HashMap<String, String>();
        params2.put("num", "6");
        params2.put("categoryId", "4");
        Map<String, Object> CMap = webPrdService.getPrdRecommendList(params2);
        model.addAttribute("CMap", CMap);

        return "index";

    }

    @RequestMapping("/verification.html")
    public String verification() {
        return "/verification";
    }

    @RequestMapping("/cms/page")
    public String cms(Model model, String pageNo, @CookieValue(value = "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE", defaultValue = "zh-CN") String i18n) {
        Map<String, Object> menusMap = webArtService.staticPageTree("top");
        model.addAttribute("menu", menusMap);
        Map<String, Object> page = webArtService.getStaticPage(pageNo);
        model.addAttribute("page", page);


        model.addAttribute("i18n", i18n);
        Map<String, Object> footer = webArtService.staticPageTree("bottom");
        model.addAttribute("footer", footer);


        Map<String, Object> indexMap = webIndexService.getPageIndexData();
        model.addAttribute("category", indexMap.get("category"));
        model.addAttribute("friendLink", indexMap.get("friendLink"));
        model.addAttribute("copyright", indexMap.get("copyright"));
        return "/cms/page";
    }

    @RequestMapping("/cms/link")
    public String link(Model model, String pageNo, @CookieValue(value = "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE", defaultValue = "zh-CN") String i18n) {
        Map<String, Object> menusMap = webArtService.staticPageTree("top");
        model.addAttribute("menu", menusMap);
        Map<String, Object> page = webArtService.getStaticPage(pageNo);
        model.addAttribute("page", page);
        Map<String, Object> indexMap = webIndexService.getPageIndexData();
        model.addAttribute("category", indexMap.get("category"));

        model.addAttribute("i18n", i18n);
        Map<String, Object> footer = webArtService.staticPageTree("bottom");
        model.addAttribute("footer", footer);

        model.addAttribute("friendLink", indexMap.get("friendLink"));
        model.addAttribute("copyright", indexMap.get("copyright"));
        return "/cms/link";
    }


    @RequestMapping("/all/sitemap")
    public void sitemap() {
        System.out.println("++++++++++++ sitemap");

        HttpServletRequest request = HttpContextUtils.getRequest();
        HttpServletResponse response = HttpContextUtils.getResponse();

        String fullUrl = request.getRequestURL().toString();
        String url = request.getRequestURI();
        String path = fullUrl.substring(0, fullUrl.indexOf(url));
        System.out.println(fullUrl);
        System.out.println(url);
        System.out.println(path);

//        String path="https://www.artplussh.cn";
        //todo:缓存
        Engine engine = Engine.use();
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.setBaseTemplatePath("/view/");
        Map<String, List<SitMapModel>> data = webIndexService.getSitMap(path);
        if (data == null) {
            data = new HashMap<>();
        }

        Template template = engine.getTemplate("sitmap.html");
        String result = template.renderToString(data);

        RenderFactory factory = new RenderFactory();
        Render render = factory.getXmlRender(result);
        render.setContext(request, response);
        render.render();
    }


    @RequestMapping("/baidu/sitemap.xml")
    public void baidu_sitemap(Model model) {
        System.out.println("++++++++++++ index");
        String path = "https://www.artplussh.cn";
        //todo:缓存
        Engine engine = Engine.use();
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.setBaseTemplatePath("/view/");
        Map<String, List<SitMapModel>> data = webIndexService.getSitMap(path);
        if (data == null) {
            data = new HashMap<>();
        }

        Template template = engine.getTemplate("sitmap.html");
        String result = template.renderToString(data);

        RenderFactory factory = new RenderFactory();
        Render render = factory.getXmlRender(result);
        render.setContext(HttpContextUtils.getRequest(), HttpContextUtils.getResponse());
        render.render();
    }

    @RequestMapping("/com/sitemap.xml")
    public void com_sitemap(Model model) {
        System.out.println("++++++++++++ index");
        String path = "https://www.artplussh.com";
        //todo:缓存
        Engine engine = Engine.use();
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.setBaseTemplatePath("/view/");
        Map<String, List<SitMapModel>> data = webIndexService.getSitMap(path);
        if (data == null) {
            data = new HashMap<>();
        }

        Template template = engine.getTemplate("sitmap.html");
        String result = template.renderToString(data);

        RenderFactory factory = new RenderFactory();
        Render render = factory.getXmlRender(result);
        render.setContext(HttpContextUtils.getRequest(), HttpContextUtils.getResponse());
        render.render();
    }


    @RequestMapping("/robots.txt")
    public void robots(Model model) {
        System.out.println("++++++++++++ index");
        String path = "https://www.artplussh.com";
        //todo:缓存
        Engine engine = Engine.use();
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.setBaseTemplatePath("/view/");
//        Map<String,List<SitMapModel>> data=webIndexService.getSitMap(path);
//        if(data==null){
//            data=new HashMap<>();
//        }

        Template template = engine.getTemplate("robots.html");
        String result = template.renderToString();

        RenderFactory factory = new RenderFactory();
        Render render = factory.getTextRender(result);
        render.setContext(HttpContextUtils.getRequest(), HttpContextUtils.getResponse());
        render.render();
    }


    @RequestMapping("/artshanghai/sitemap.xml")
    public void artshanghai_sitemap(Model model) {
        System.out.println("++++++++++++ index");
        String path = "https://www.artshanghaifair.com";
        //todo:缓存
        Engine engine = Engine.use();
        engine.setDevMode(true);
        engine.setToClassPathSourceFactory();
        engine.setBaseTemplatePath("/view/");
        Map<String, List<SitMapModel>> data = webIndexService.getSitMap(path);
        if (data == null) {
            data = new HashMap<>();
        }

        Template template = engine.getTemplate("sitmap.html");
        String result = template.renderToString(data);

        RenderFactory factory = new RenderFactory();
        Render render = factory.getXmlRender(result);
        render.setContext(HttpContextUtils.getRequest(), HttpContextUtils.getResponse());
        render.render();
    }


    @RequestMapping("/getfile")
    public void getfile() {
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("姓名", "张三");
        row1.put("年龄", 23);
        row1.put("成绩", 88.32);
        row1.put("是否合格", true);
        row1.put("考试日期", DateUtil.date());

        Map<String, Object> row2 = new LinkedHashMap<>();
        row2.put("姓名", "李四");
        row2.put("年龄", 33);
        row2.put("成绩", 59.50);
        row2.put("是否合格", false);
        row2.put("考试日期", DateUtil.date());


        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流


        HttpServletResponse response = HttpContextUtils.getResponse();

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.xls");

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
